# -*- coding: utf-8 -*-
from web.controllers.api import route_api
from flask import request, jsonify
from application import app, db
import requests, json
from common.models.member.Member import Member
from common.models.device.CheckList import CheckList
from common.models.device.DeviceRelation import DeviceRelation


# 首次登录
@route_api.route("/member/login", methods=["GET", "POST"])
def login():
    resp = {'error': 200, 'msg': '操作成功', 'data': {}}

    content = request.get_json()
    app.logger.info(content)
    usercode = content['usercode']
    userpasswd = content['userpasswd']

    # usercode = request.form.get("usercode")
    # userpasswd = request.form.get("userpasswd")

    app.logger.info(usercode)
    app.logger.info(userpasswd)

    if not usercode or len(usercode) < 1:
        resp['error'] = -1
        resp['msg'] = "code长度错误"
        return jsonify(resp)

    if not userpasswd or len(userpasswd) < 1:
        resp['error'] = -2
        resp['msg'] = "密码长度错误"
        return jsonify(resp)

    member_info = Member.query.filter_by(usercode=usercode, userpasswd=userpasswd).first()

    if not member_info:
        resp['error'] = -3
        resp['msg'] = "用户不存在"
        return jsonify(resp)

    resp['data'] = {
        'userstatus': member_info.role
    }

    return jsonify(resp)


@route_api.route("/member/testman", methods=["GET", "POST"])
def testman():
    resp = {'error': 200, 'msg': '操作成功', 'testmanInfo': []}

    member_info_list = Member.query.filter_by(role="2").all()

    testman_list = []
    for member_item in member_info_list:
        testman_list.append(member_item.nickname)

    resp['testmanInfo'] = testman_list

    return jsonify(resp)


# 根据status返回不同的主页信息
@route_api.route("/member/home", methods=["GET", "POST"])
def home():
    resp = {'error': 200, 'nickname': ' ', 'msg': '操作成功', 'data': []}
    content = request.get_json()

    usercode = content['usercode']
    role = content['userstatus']

    if not usercode or len(usercode) < 1:
        resp['error'] = -1
        resp['msg'] = "code长度错误"
        return jsonify(resp)

    member_info = Member.query.filter_by(usercode=usercode, role=role).first()
    if not member_info:
        resp['error'] = -3
        resp['msg'] = "用户不存在"
        return jsonify(resp)

    member_id = member_info.id
    resp['nickname'] = member_info.nickname


    # 用户
    if role == "0":
        # 如果是用戶的話，根据用户id可以查到此用户所有得提交列表,这是一个list
        checklist_list = CheckList.query.filter_by(member_id=member_id).order_by(CheckList.update_time.desc()).all()

        if not checklist_list:
            resp['error'] = -4
            resp['msg'] = "此用户没有提交过任何数据"
            return jsonify(resp)
        data = []

        for checklist_item in checklist_list:
            data_item = dict()
            data_item['device_num'] = checklist_item.device_number
            data_item['company'] = checklist_item.company
            data_item['date'] = checklist_item.commission_date
            data_item['status'] = checklist_item.member_status
            data_item['check_id'] = checklist_item.id
            data.append(data_item)

        resp['data'] = data
        return jsonify(resp)

    # 管理員
    if role == "1":
        # 如果是管理员，那么就列出check_list得所有数据,但是不包括未提交得数据，这是一个list
        checklist_list = CheckList.query.filter(CheckList.member_status != "待提交").order_by(CheckList.create_time.desc()).all()

        if not checklist_list:
            resp['error'] = -4
            resp['msg'] = "还没有用户提交过数据"
            return jsonify(resp)

        data = []
        for checklist_item in checklist_list:
            data_item = dict()
            data_item['device_num'] = checklist_item.device_number
            data_item['company'] = checklist_item.company
            data_item['date'] = checklist_item.commission_date
            data_item['status'] = checklist_item.administor_status
            data_item['check_id'] = checklist_item.id
            data.append(data_item)

        resp['data'] = data
        return jsonify(resp)
    # 測試人員,太难了
    if role == "2":
        # 获取此测试员名下所有得设备列表，这是一个list

        device_info_list = DeviceRelation.query.filter_by(testman_name=member_info.nickname).order_by(DeviceRelation.update_time.desc()).all()
        if not device_info_list:
            resp['error'] = -5
            resp['msg'] = "还没有分配测试"
            return jsonify(resp)
        data = []
        checkid_list = []
        for device_info_item in device_info_list:
            check_id = device_info_item.check_id
            checkid_list.append(check_id)

        # 去除重复check_id,获取一个新的list
        check_id_list_no_repeat = list(set(checkid_list))
        for check_id_item in check_id_list_no_repeat:
            data_item = dict()
            device_number = checkid_list.count(check_id_item)
            checklist_info = CheckList.query.filter_by(id=check_id_item).first()

            data_item['device_num'] = device_number
            data_item['company'] = checklist_info.company
            data_item['date'] = checklist_info.commission_date
            deviceHH = DeviceRelation.query.filter_by(check_id=check_id_item, testman_name=member_info.nickname).first()
            data_item['status'] = deviceHH.test_status
            data_item['check_id'] = checklist_info.id
            data_item['update_time'] = checklist_info.update_time
            data.append(data_item)

        new_data = sorted(data, key=lambda x: x['update_time'], reverse=True)

        resp['data'] = new_data
        return jsonify(resp)


# url = "https://api.weixin.qq.com/sns/jscode2session?appid={0}&secret={1}&js_code={2}&grant_type=authorization_code"\
    #   .format(app.config['MINA_APP']['appid'], app.config['MINA_APP']['appkey'], code)

    # r = requests.get(url)
    # res = json.loads(r.text)

    # openid = res['openid'] if 'openid' in res else ''
